<template>
  <van-popup
    :show="visible"
    position="bottom"
    :style="{ height: '70%' }"
    round
    @update:show="$emit('update:visible', $event)"
  >
    <div class="login-form">
      <h2>{{ isRegister ? '注册' : '登录' }}</h2>

      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />

          <van-field
            v-if="isRegister"
            v-model="email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱（可选）"
            type="email"
          />

          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]"
          />

          <van-field
            v-if="isRegister"
            v-model="confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请确认密码' },
              { validator: validatePasswordMatch, message: '两次输入的密码不一致' }
            ]"
          />
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit" :loading="isLoading">
            {{ isRegister ? '注册' : '登录' }}
          </van-button>

          <div class="form-footer">
            <a @click="toggleForm">{{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}</a>
          </div>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import { showToast } from 'vant';
import { authApi } from '../api';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'login-success']);

// 表单数据
const username = ref('');
const email = ref('');
const password = ref('');
const confirmPassword = ref('');
const isRegister = ref(false);
const isLoading = ref(false);

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    resetForm();
  }
});

// 切换登录/注册表单
const toggleForm = () => {
  isRegister.value = !isRegister.value;
  resetForm();
};

// 重置表单
const resetForm = () => {
  username.value = '';
  email.value = '';
  password.value = '';
  confirmPassword.value = '';
};

// 验证密码是否匹配
const validatePasswordMatch = () => {
  return password.value === confirmPassword.value;
};

// 提交表单
const onSubmit = async () => {
  try {
    isLoading.value = true;

    if (isRegister.value) {
      // 注册
      if (password.value !== confirmPassword.value) {
        showToast('两次输入的密码不一致');
        return;
      }

      const response = await authApi.register({
        username: username.value,
        password: password.value,
        email: email.value || null
      });

      showToast('注册成功');
      emit('login-success', response.user);
    } else {
      // 登录
      const response = await authApi.login({
        username: username.value,
        password: password.value
      });

      showToast('登录成功');
      emit('login-success', response.user);
    }

    emit('update:visible', false);
  } catch (error) {
    console.error('Authentication error:', error);
    if (error.response && error.response.data && error.response.data.error) {
      showToast(error.response.data.error);
    } else {
      showToast(isRegister.value ? '注册失败' : '登录失败');
    }
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.login-form {
  padding: 20px;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 20px;
}

.form-footer {
  margin-top: 16px;
  text-align: center;
}

.form-footer a {
  color: #1989fa;
  cursor: pointer;
}
</style>
